package com.xcjh.utils;

import cn.hutool.core.io.FileUtil;
import com.xcjh.exception.GlobalException;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class UploadUtils {

    @Value("${static.path}")
    private String path;

    public static String getUrl(String path,HttpServletRequest request, MultipartFile file,String type){

        if (!FileSizeUtil.checkFileSize(file.getSize(), 20, "M")){
            throw new GlobalException("文件过大，请重新选择");
        }
        String filename = null;
        if (file != null) {
            InputStream in = null;
            OutputStream out = null;
            try {
                String OriginalFilename = file.getOriginalFilename();// 获取该文件的原文件名
                String extension = FilenameUtils.getExtension(OriginalFilename);
                filename = System.currentTimeMillis() + "." + extension;// 利用时间戳给文件重命名，解决名字可能重复的问题
                //String path = request.getServletContext().getRealPath("/" + type);// 获取文件的动态根路径
                //path = "/Users/admin/Desktop/my/user-server/src/main/webapp" + "/"+type;
                path = path + type;
                File file2 = new File(path);// 创建一个该路径的文件
                if (!file2.exists()) {// 如果文件不存在
                    file2.mkdirs();// 就创建一个
                }
                in = file.getInputStream();// 获取输入流
                out = new FileOutputStream(new File(file2, filename));// 获取输出流，并把文件父路径和文件名传入
                IOUtils.copy(in, out);// 进行文件复制
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (out != null) {
                    try {
                        out.close();// 关流
                        if (in != null) {
                            in.close();// 关流
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return path +"/"+ filename;
    }



}
